package com.geping.etl.utils.common;

import java.io.*;
import java.util.Properties;

/**
 * @Author: wangzd
 * @Date: 14:52 2019/11/15
 */
public class PropertiesUtil {

    /**
     * 读取配置文件Properties
     *
     * @author wangzd
     */
    private PropertiesUtil() {
    }

    private static class SingletonHolder {
        private static final PropertiesUtil instance = new PropertiesUtil();
    }

    public static PropertiesUtil getInstance() {
        return SingletonHolder.instance;
    }

    /**
     * 获取Properties对象
     *
     * @param file 文件名
     * @return
     */
    public Properties getProp(String file) {
        InputStream in = null;
        BufferedReader bf = null;
        Properties prop = new Properties();
        try {
            in = this.getClass().getClassLoader().getResourceAsStream(file);
            bf = new BufferedReader(new InputStreamReader(in, "UTF-8"));
            prop.load(bf);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (bf != null) {
                    bf.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return prop;
    }

    /**
     * 根据系统快速获取linuxpath与path配置文件
     * @return
     */
    public Properties getPropToPath() {
        return this.getPropByOsName("linuxpath.properties","path.properties");
    }

    /**
     * 根据系统快速获取配置文件
     * @param linuxProp Linux系统配置文件名
     * @param otherProp 其它系统配置文件名
     * @return
     */
    public Properties getPropByOsName(String linuxProp, String otherProp) {
        Properties prop;
        String property = System.getProperty("os.name");
        if ("Linux".equals(property)) {
            prop = this.getProp(linuxProp);
        } else {
            prop = this.getProp(otherProp);
        }
        return prop;
    }

    /**
     * 读取key字段，配置文件在classes根路径下xx.properties，在子路径下xx/xx.properties
     *
     * @param file
     * @param key
     * @return
     */
    public String read(String file, String key) {
        InputStream in = this.getClass().getClassLoader().getResourceAsStream(file);
        BufferedReader bf = null;
        try {
            bf = new BufferedReader(new InputStreamReader(in, "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        Properties prop = new Properties();
        String value = "";
        try {
            prop.load(bf);
            value = prop.getProperty(key);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return value;
    }
}
